$(document).ready(function(){
    init();
})

let recommendBooks = [];

function getSlideShow(pageSize) {
    var result;
    var formData = new FormData();
    formData.append("pageSize", pageSize);
    $.ajax({
        type: "post",
        url: "/api/book/v/getSlideshow",
        async: false,
        dataType: "text",
        data: formData,
        processData: false,
        contentType: false,
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                result = JSON.parse(data.data);
            }else {
                result = [];
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return result;
}

/* 获得新书 */
function getNewBooks(pageSize) {
    var result;
    var formData = new FormData();
    formData.append("pageSize", pageSize);
    formData.append("pageNum", 1);
    $.ajax({
        type: "post",
        url: "/api/book/v/page/getPageBooksByTime",
        async: false,
        dataType: "text",
        data: formData,
        processData: false,
        contentType: false,
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                result = JSON.parse(data.data);
            }else {
                result = [];
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return result;
}

function fillSildeShow() {
    var slideShowBooks = getSlideShow(2);
    var reg = new RegExp("\"", "g");
    var img1 = "url(..//..//images//" + slideShowBooks[0].bookImg.replace(reg, "") + ")";
    var img2 = "url(..//..//images//" + slideShowBooks[1].bookImg.replace(reg, "") + ")";
    $(".bg-1").first().css("cursor", "pointer");
    $(".bg-1").first().css("background-image", img1);
    $(".bg-1").first().attr("bookIsbn",slideShowBooks[0].bookIsbn);
    $(".bg-1").first().css("cursor", "pointer");
    $(".bg-2").first().css("background-image", img2);
    $(".bg-2").first().attr("bookIsbn",slideShowBooks[1].bookIsbn);
    console.log($(".bg-1").first().css("background-image"));
    console.log($(".bg-2").first().css("background-image"));
}

function fillFourBooks() {
    var books = getSlideShow(4);
    var reg = new RegExp("\"", "g");
    for (var i=0;i<4;i++) {
        var img1 = "..//..//images//" + books[i].bookImg.replace(reg, "");
        $("div.banner-img>a[name='fourBook']>img").eq(i).attr("src", img1);
        $("div.banner-img>a[name='fourBook']>img").css("height", "270px");
        $("div.banner-img>a[name='fourBook']").eq(i).attr("href", "bookDetails?bookIsbn=" + books[i].bookIsbn);
    }
}

function fillNewBooks() {
    var books = getNewBooks(10);
    books.forEach(book => {
        $("div[name='newBook']").append(getNewBookTemplate(book));
    })
}

/* 获得新书列表模板 */
function getNewBookTemplate(book) {
    var reg = new RegExp("\"", "g");
    var template = "<div class='slide-item'>" +
        "<div class='single-product'>" +
        "<div class='product-img'>" +
        "<a href='bookDetails?bookIsbn=" + book.bookIsbn + "'>" +
        "<img class='primary-img' style='height: 248px; width: auto' src='..//..//images//" + book.bookImg.replace(reg, "") + "' alt='Umino's Product Image'>" +
        "</a>" +
        "<div class='add-actions' isbn='" + book.bookIsbn + "'>" +
        "<ul>" +
        // "<li><a href='javascript: void(0);' data-toggle='tooltip' data-placement='top' title='加入购物车'><i class='ion-bag'></i></a></li>" +
        "<li><a href='javascript: void(0);' data-toggle='tooltip' data-placement='top' title='加入收藏'><i class='ion-ios-heart-outline'></i></a></li>" +
        "</ul>" +
        "</div>" +
        "</div>" +
        "<div class='product-content'>" +
        "<div class='product-desc_info'>" +
        "<div class='price-box'>" +
        "<span class='new-price'>￥" + book.bookPrice + "</span>" +
        // "<span class='old-price'>￥45.00</span>" +
        "</div>" +
        "<h6 class='product-name'><a href='bookDetails?bookIsbn=" + book.bookIsbn + "'>" + book.bookName +"</a>" +
        "</h6>" +
        "<div class='product-progressbar product-progressbar-3'>" +
        "<span class='product-in_stock'>作者:<strong>" + book.bookAuthor + "</strong></span>" +
        "</div>" +
        "<div class='product-progressbar product-progressbar-3'>" +
        "<span class='product-sold'>出版社:<strong>" + book.bookPublishers + "</strong></span>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>";
    return template;
}

/* 获得分页的图书 */
function getAllBooksByPage(pageNum, pageSize) {
    var result;
    var formData = new FormData();
    formData.append("pageSize", pageSize);
    formData.append("pageNum", pageNum);
    $.ajax({
        type: "post",
        url: "/api/book/v/page/getPageBooksAll",
        async: false,
        dataType: "text",
        data: formData,
        processData: false,
        contentType: false,
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                result = JSON.parse(data.data);
            }else {
                result = [];
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return result;
}

/* 获得书籍列表的模板 */
function getBookTemplate(book) {
    var reg = new RegExp("\"", "g");
    return "<div class='slide-item'>" +
        "<div class='single-product'>" +
        "<div class='product-img'>" +
        "<a href='bookDetails?bookIsbn=" + book.bookIsbn + "'>" +
        "<img class='primary-img' style='height: 188px; width: auto' src='..//..//images//" + book.bookImg.replace(reg, "") + "' alt='Umino's Product Image'>" +
        "</a>" +
        "<div class='add-actions' isbn='" + book.bookIsbn + "'>" +
        "<ul>" +
        // "<li><a href='javascript: void(0);' data-toggle='tooltip' data-placement='top' title='加入购物车'><i class='ion-bag'></i></a></li>" +
        "<li><a href='javascript: void(0);' data-toggle='tooltip' data-placement='top' title='加入收藏'><i class='ion-ios-heart-outline'></i></a></li>" +
        "</ul>" +
        "</div>" +
        "</div>" +
        "<div class='product-content'>" +
        "<div class='product-desc_info'>" +
        "<div class='price-box'>" +
        "<span class='new-price'>￥" + book.bookPrice + "</span>" +
        // "<span class='old-price'>￥460.00</span>" +
        "</div>" +
        "<h6 class='product-name'><a href='bookDetails?bookIsbn=" + book.bookIsbn + "'>" + book.bookName + "</a>" +
        "</h6>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>";
}

function actionClickEvent() {
    $("div.add-actions>ul li").on("click", function() {
        addRelation(this);
    })
}

function fillBooks() {
    var book1s = getAllBooksByPage(1, 6);
    var book2s = getAllBooksByPage(2, 6);
    book1s.forEach(book => {
        $("div[name='book1']").append(getBookTemplate(book));
    });
    book2s.forEach(book => {
        $("div[name='book2']").append(getBookTemplate(book));
    });
}

function addRelation(e) {
    let content = $(e).find("a").attr("title");
    let relation;
    if (content.indexOf("收藏") > -1) {
        relation = "收藏";
    }else if (content.indexOf("购物车") > -1) {
        relation = "购物车";
    }else {
        return false;
    }
    let isbn = $(e).parentsUntil(".single-product").find("div.add-actions").attr("isbn");
    $.ajax({
        type: "POST",
        url: "/api/userBookRelation/u/addUserBookRelation",
        dataType: "text",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify({
            "bookIsbn": isbn,
            "relation": relation
        }),
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                if (relation == "收藏")
                    alert("收藏成功");
                else if (relation == "购物车")
                    alert("加入购物车成功");
                updateRecommendBooks();
            }else {
                alert(data.msg + ", 请前往购物车或者收藏页面查看");
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    })
    initRelationBook();
}

function getRecommendBooks() {
    let result;
    $.ajax({
        type: "get",
        url: "/api/recommendBook/u/getRecommendBooks",
        async: false,
        dataType: "text",
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                result = JSON.parse(data.data);
            }else {
                result = [];
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return result;
}

function getRecommendBookTemplate(book) {
    return "<div class='slide-item' style='margin-bottom: 10px'>" +
        "<div class='single-product'>" +
        "<div class='product-img'>" +
        "<a href='bookDetails?bookIsbn=" + book.bookIsbn + "'>" +
        "<img style='height: 130px; width: auto' src='..//..//images//" + book.bookImg.replace(reg, "") + "' alt=Umino's Product Image>" +
        "</a>" +
        "</div>" +
        "<div class='product-content'>" +
        "<div class='product-desc_info'>" +
        "<div class='price-box'>" +
        "<span class='new-price'>￥" + book.bookPrice + "</span>" +
        // "<span class=old-price>￥66.00</span>" +
        "</div>" +
        "<h6 class='product-name'><a href='bookDetails?bookIsbn=" + book.bookIsbn + "'>" + book.bookName + "</a>" +
        "</h6>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>"
}

function init() {
    /* 轮播图 */
    fillSildeShow();
    /* 获取随机四本书 */
    fillFourBooks();
    /* 新书 */
    fillNewBooks();
    $('.umino-product_slider').slick({
        infinite: false,
        arrows: false,
        dots: true,
        speed: 2000,
        slidesToShow: 4,
        slidesToScroll: 2,
        prevArrow: '<button class="slick-prev"><i class="ion-ios-arrow-back"></i></button>',
        nextArrow: '<button class="slick-next"><i class="ion-ios-arrow-forward"></i></button>',
        responsive: [
            {
                breakpoint: 1501,
                settings: {
                    slidesToShow: 4
                }
            },
            {
                breakpoint: 1200,
                settings: {
                    slidesToShow: 4
                }
            },
            {
                breakpoint: 992,
                settings: {
                    slidesToShow: 2
                }
            },
            {
                breakpoint: 768,
                settings: {
                    slidesToShow: 2
                }
            },
            {
                breakpoint: 575,
                settings: {
                    slidesToShow: 1
                }
            }
        ]
    });
    fillBooks();
    actionClickEvent();
    $('.umino-product_slider-2').slick({
        infinite: true,
        arrows: false,
        dots: false,
        speed: 2000,
        slidesToShow: 5,
        slidesToScroll: 1,
        prevArrow: '<button class="slick-prev"><i class="ion-ios-arrow-back"></i></button>',
        nextArrow: '<button class="slick-next"><i class="ion-ios-arrow-forward"></i></button>',
        responsive: [
            {
                breakpoint: 1501,
                settings: {
                    slidesToShow: 4
                }
            },
            {
                breakpoint: 1200,
                settings: {
                    slidesToShow: 4
                }
            },
            {
                breakpoint: 992,
                settings: {
                    slidesToShow: 2
                }
            },
            {
                breakpoint: 768,
                settings: {
                    slidesToShow: 2
                }
            },
            {
                breakpoint: 575,
                settings: {
                    slidesToShow: 1
                }
            }
        ]
    });
    $('.umino-product_slider-3').slick({
        infinite: true,
        arrows: false,
        dots: false,
        speed: 2000,
        slidesToShow: 3,
        slidesToScroll: 1,
        rows: 2,
        prevArrow: '<button class="slick-prev"><i class="ion-ios-arrow-back"></i></button>',
        nextArrow: '<button class="slick-next"><i class="ion-ios-arrow-forward"></i></button>',
        responsive: [
            {
                breakpoint: 1501,
                settings: {
                    slidesToShow: 3
                }
            },
            {
                breakpoint: 1200,
                settings: {
                    slidesToShow: 3
                }
            },
            {
                breakpoint: 992,
                settings: {
                    slidesToShow: 2
                }
            },
            {
                breakpoint: 768,
                settings: {
                    slidesToShow: 2
                }
            },
            {
                breakpoint: 575,
                settings: {
                    slidesToShow: 1
                }
            }
        ]
    });
    recommendBooks = getRecommendBooks();
    recommendBooks.forEach((book, ind) => {
        let dom = "#recommend_area div.recommend_book"+(ind%3+1);
        $(dom).append(getRecommendBookTemplate(book));
    })
}